<?php
namespace app\common\loglic;

use app\common\loglic\Model;

class Tag extends Model
{
    //自增更新
    public function incUpdate($pkId=0, $field='tag_weight', $num=1, $time=0)
    {
        if(!$pkId){
            return 0;
        }
        return db('tag')->where('tag_id',$pkId)->setInc($field, abs($num), $time);
    }

    //自减
    public function decUpdate($pkId=0, $field='tag_weight', $num=1, $time=0)
    {
        if(!$pkId){
            return 0;
        }
        return db('tag')->where('tag_id',$pkId)->setDec($field, abs($num), $time);
    }

    //更新字段值
    public function fieldUpdate($ids=[], $field='tag_status', $value='normal')
    {
        if(!$ids || !$value){
            return false;
        }
        return db('tag')->where('tag_id','in',$ids)->setField($field, $value);
    }

    //更新统计
    public function updateCount()
    {
        $this->dbUpdate('tag',[['tag_id','gt',0]],['tag_count'=>0]);
        //分组查询统计
        $item = db('tag_map')
        ->field('tag_mp_tid as tag_id,count(tag_mp_tid) as tag_count')
        ->where('tag_mp_tid > 0')
        ->group('tag_mp_tid')
        ->order('tag_count desc')
        ->select();
        //批量更新
        if($item){
            return model('common/Tag')->allowField(true)->isUpdate(true)->saveAll($item);
        }
        return 0;
    }

    //按主键ID删除
    public function deleteId($typeId=0)
    {
        if(!$typeId){
            return 0;
        }
        return $this->modelDelete('common/Tag', ['tag_id'=>$typeId], 'tagMap');
    }
}